
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Node学习(九)--Websocket - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,WebSocket的优势1.性能高。
根据测试环境数据的不同，大约会比普通Ajax请求高2-10倍。 HTTP是文本协议，数据量比较大。
而WebSocket是基于二进制的协议，在建立连接时用的虽然,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">Node学习(九)--Websocket</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Node"><b>「
                    </b>NODE<b> 」</b></a>
                
                April 20, 2019
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2019/04/20/Node/Node%E5%AD%A6%E4%B9%A0(%E4%B9%9D)%20--Websocket/" title="Node学习(九)--Websocket" class="">Node学习(九)--Websocket</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    49k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    45 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Node/" rel="tag">Node</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="WebSocket的优势"><a href="#WebSocket的优势" class="headerlink" title="WebSocket的优势"></a>WebSocket的优势</h1><p>1.性能高。</p>
<p>根据测试环境数据的不同，大约会比普通Ajax请求高2-10倍。 HTTP是文本协议，数据量比较大。</p>
<p>而WebSocket是基于二进制的协议，在建立连接时用的虽然是文本数据，但之后传输的都是二进制数据，因此性能比Ajax请求高。</p>
<p>2.双向通信。</p>
<p>如果是普通Ajax请求，需要实时获取数据，只能用计时器定时发送请求，这样会浪费服务器资源和流量。</p>
<p>而通过WebSocket，服务器可以主动向前端发送信息。</p>
<p>3.安全性高</p>
<p>由于WebSocket出现较晚，相比HTTP协议，在安全性上考虑的更加充分。</p>
<p>接下来，尝试用<code>Socket.io</code>建立一个基于WebSocket的双向通信。</p>
<h2 id="Socket-io"><a href="#Socket-io" class="headerlink" title="Socket.io"></a>Socket.io</h2><p><code>Socket.io</code>是在使用WebSocket时的一个常用库，它会自动判断在支持WebSocket的浏览器中使用WebSocket，在其他浏览器中，会使用如flash等方式完成通信。</p>
<p>1.操作简单<br>2.兼容低端浏览器，如IE6<br>3.自动进行数据解析<br>4.自动重连 若出现连接断开的情况，WebSocket会进行自动重连。</p>
<h2 id="使用Socket-io建立一个WebSocket应用"><a href="#使用Socket-io建立一个WebSocket应用" class="headerlink" title="使用Socket.io建立一个WebSocket应用"></a>使用Socket.io建立一个WebSocket应用</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>)</span><br><span class="line"><span class="keyword">const</span> io = <span class="built_in">require</span>(<span class="string">'socket.io'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 1. 建立HTTP服务器。</span></span><br><span class="line"><span class="keyword">const</span> server = http.createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">server.listen(<span class="number">8080</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2. 建立WebSocket，让socket.io监听HTTP服务器，一旦发现是WebSocket请求，则会自动进行处理。</span></span><br><span class="line"><span class="keyword">const</span> ws = io.listen(server)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 建立连接完成后，触发connection事件。</span></span><br><span class="line"><span class="comment">// 该事件会返回一个socket对象（https://socket.io/docs/server-api/#Socket），可以利用socket对象进行发送、接收数据操作。</span></span><br><span class="line">ws.on(<span class="string">'connection'</span>, (socket) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 根据事件名，向客户端发送数据，数据数量不限。</span></span><br><span class="line">  socket.emit(<span class="string">'msg'</span>, <span class="string">'服务端向客户端发送数据第一条'</span>, <span class="string">'服务端向客户端发送数据第二条'</span>)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 根据事件名接收客户端返回的数据</span></span><br><span class="line">  socket.on(<span class="string">'msg'</span>, (...msgs) =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(msgs)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 使用计时器向客户端发送数据</span></span><br><span class="line">  setInterval(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    socket.emit(<span class="string">'timer'</span>, <span class="keyword">new</span> <span class="built_in">Date</span>().getTime())</span><br><span class="line">  &#125;, <span class="number">500</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"ie=edge"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="comment">&lt;!-- 引用Socket.io的客户端js文件，由于Socket.io已在服务端监听了HTTP服务器的请求，一旦收到对该文件的请求，则会自动返回该文件，不需要开发人员配置。 --&gt;</span></span><br><span class="line">  <span class="comment">&lt;!-- 该文件在服务端的位置为/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://localhost:8080/socket.io/socket.io.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="actionscript">    <span class="comment">// 与服务器建立WebSocket连接，该连接为ws协议，socket.io不需要担心跨域问题。</span></span></span><br><span class="line"><span class="actionscript">    <span class="keyword">const</span> socket = io.connect(<span class="string">'ws://localhost:8080/'</span>)</span></span><br><span class="line"></span><br><span class="line"><span class="actionscript">    <span class="comment">// 根据事件名，向服务端发送数据，数据数量不限。</span></span></span><br><span class="line"><span class="actionscript">    socket.emit(<span class="string">'msg'</span>, <span class="string">'客户端向服务端发送数据第一条'</span>, <span class="string">'客户端向服务端发送数据第二条'</span>)</span></span><br><span class="line"></span><br><span class="line"><span class="actionscript">    <span class="comment">// 根据事件名接收服务端返回的数据</span></span></span><br><span class="line"><span class="actionscript">    socket.on(<span class="string">'msg'</span>, (...msgs) =&gt; &#123;</span></span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(msgs)</span></span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line"><span class="actionscript">    <span class="comment">// 接收服务端通过计时器发送来的数据</span></span></span><br><span class="line"><span class="actionscript">    socket.on(<span class="string">'timer'</span>, (time) =&gt; &#123;</span></span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(time)</span></span><br><span class="line">    &#125;)</span><br><span class="line">  <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>用浏览器打开index.html，即可在控制台看到打印的消息。</p>
<h1 id="原生实现WebSocket应用"><a href="#原生实现WebSocket应用" class="headerlink" title="原生实现WebSocket应用"></a>原生实现WebSocket应用</h1><p>上面使用了Socket.io实现WebSocket，也是开发中常用的方式。</p>
<p>但这样不利于了解其原理，这里使用Nodejs的Net模块和Web端的WebSocket API实现WebSocket服务器。</p>
<h2 id="服务端创建一个Net服务器"><a href="#服务端创建一个Net服务器" class="headerlink" title="服务端创建一个Net服务器"></a>服务端创建一个Net服务器</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入net模块</span></span><br><span class="line"><span class="keyword">const</span> net = <span class="built_in">require</span>(<span class="string">'net'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用net模块创建服务器，返回的是一个原始的socket对象，与Socket.io的socket对象不同。</span></span><br><span class="line"><span class="keyword">const</span> server = net.createServer(<span class="function">(<span class="params">socket</span>) =&gt;</span> &#123;</span><br><span class="line">  </span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">server.listen(<span class="number">8080</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Web端创建一个WebSocket链接"><a href="#Web端创建一个WebSocket链接" class="headerlink" title="Web端创建一个WebSocket链接"></a>Web端创建一个WebSocket链接</h2><p>创建一个WebSocket连接，此时控制台的Network模块可以看到一个处于pending状态的HTTP连接。</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/3/13/16977a451448747d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="socket"></p>
<p>这个连接是一个HTTP请求，与普通HTTP请求的请求你头相比，增加了以下内容：</p>
<ul>
<li>Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits  // 扩展信息</li>
<li>Sec-WebSocket-Key: O3PKSb95qaSB7/+XfaTg7Q== // 发送一个Key到服务端，用于校验服务端是否支持WebSocket</li>
<li>Sec-WebSocket-Version: 13 // WebSocket版本</li>
<li>Upgrade: websocket  // 告知服务器通信协议将会升级到WebSocket若服务器支持则继续下一步</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> ws = <span class="keyword">new</span> WebSocket(<span class="string">'ws://localhost:8080/'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="服务端使用socket-once，触发一次data事件处理HTTP请求头数据"><a href="#服务端使用socket-once，触发一次data事件处理HTTP请求头数据" class="headerlink" title="服务端使用socket.once，触发一次data事件处理HTTP请求头数据"></a>服务端使用socket.once，触发一次data事件处理HTTP请求头数据</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">socket.once(<span class="string">'data'</span>, (buffer) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 接收到HTTP请求头数据</span></span><br><span class="line">  <span class="keyword">const</span> str = buffer.toString()</span><br><span class="line">  <span class="built_in">console</span>.log(str)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>打印结果如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">GET / HTTP/<span class="number">1.1</span></span><br><span class="line">Host: localhost:<span class="number">8080</span></span><br><span class="line">Connection: Upgrade</span><br><span class="line">Pragma: no-cache</span><br><span class="line">Cache-Control: no-cache</span><br><span class="line">Upgrade: websocket</span><br><span class="line">Origin: file:<span class="comment">//</span></span><br><span class="line">Sec-WebSocket-Version: <span class="number">13</span></span><br><span class="line">User-Agent: Mozilla/<span class="number">5.0</span> (Windows NT <span class="number">10.0</span>; Win64; x64) AppleWebKit/<span class="number">537.36</span> (KHTML,</span><br><span class="line">like Gecko) Chrome/<span class="number">72.0</span><span class="number">.3626</span><span class="number">.121</span> Safari/<span class="number">537.36</span></span><br><span class="line">Accept-Encoding: gzip, deflate, br</span><br><span class="line">Accept-Language: zh-CN,zh;q=<span class="number">0.9</span></span><br><span class="line">Cookie: _ga=GA1<span class="number">.1</span><span class="number">.1892261700</span><span class="number">.1545540050</span>; _gid=GA1<span class="number">.1</span><span class="number">.774798563</span><span class="number">.1552221410</span>; io=<span class="number">7</span>X0VY8jhwRTdRHBfAAAB</span><br><span class="line">Sec-WebSocket-Key: JStOineTIKaQskxefzer7Q==</span><br><span class="line">Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits</span><br></pre></td></tr></table></figure>
<p>将回车符转换为\r\n显示，结果如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET / HTTP/<span class="number">1.1</span>\r\nHost: localhost:<span class="number">8080</span>\r\nConnection: Upgrade\r\nPragma: no-cache\r\nCache-Control: no-cache\r\nUpgrade: websocket\r\nOrigin: file:<span class="comment">//\r\nSec-WebSocket-Version: 13\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh;q=0.9\r\nCookie: _ga=GA1.1.1892261700.1545540050; _gid=GA1.1.774798563.1552221410; io=7X0VY8jhwRTdRHBfAAAB\r\nSec-WebSocket-Key: dRB1xDJ/vV+IAGnG7TscNQ==\r\nSec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\r\n</span></span><br></pre></td></tr></table></figure>
<h2 id="将请求头字符串转为对象"><a href="#将请求头字符串转为对象" class="headerlink" title="将请求头字符串转为对象"></a>将请求头字符串转为对象</h2><p>创建一个parseHeader方法处理请求头。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parseHeader</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 将请求头数据按回车符切割为数组，得到每一行数据</span></span><br><span class="line">  <span class="keyword">let</span> arr = str.split(<span class="string">'\r\n'</span>).filter(<span class="function"><span class="params">item</span> =&gt;</span> item)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 第一行数据为GET / HTTP/1.1，可以丢弃。</span></span><br><span class="line">  arr.shift()</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(arr)</span><br><span class="line">  <span class="comment">/* </span></span><br><span class="line"><span class="comment">    处理结果为：</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    [ 'Host: localhost:8080',</span></span><br><span class="line"><span class="comment">      'Connection: Upgrade',</span></span><br><span class="line"><span class="comment">      'Pragma: no-cache',</span></span><br><span class="line"><span class="comment">      'Cache-Control: no-cache',</span></span><br><span class="line"><span class="comment">      'Upgrade: websocket',</span></span><br><span class="line"><span class="comment">      'Origin: file://',</span></span><br><span class="line"><span class="comment">      'Sec-WebSocket-Version: 13',</span></span><br><span class="line"><span class="comment">      'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',</span></span><br><span class="line"><span class="comment">      'Accept-Encoding: gzip, deflate, br',</span></span><br><span class="line"><span class="comment">      'Accept-Language: zh-CN,zh;q=0.9',</span></span><br><span class="line"><span class="comment">      'Cookie: _ga=GA1.1.1892261700.1545540050; _gid=GA1.1.774798563.1552221410; io=7X0VY8jhwRTdRHBfAAAB',</span></span><br><span class="line"><span class="comment">      'Sec-WebSocket-Key: jqxd7P0Xx9TGkdMfogptRw==',</span></span><br><span class="line"><span class="comment">      'Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits' ]</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> headers = &#123;&#125;  <span class="comment">// 存储最终处理的数据</span></span><br><span class="line"></span><br><span class="line">  arr.forEach(<span class="function">(<span class="params">item</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 需要用":"将数组切割成key和value</span></span><br><span class="line">    <span class="keyword">let</span> [name, value] = item.split(<span class="string">':'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 去除无用的空格，将属性名转为小写</span></span><br><span class="line">    name = name.replace(<span class="regexp">/^\s|\s+$/g</span>, <span class="string">''</span>).toLowerCase()</span><br><span class="line">    value = value.replace(<span class="regexp">/^\s|\s+$/g</span>, <span class="string">''</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取所有的请求头属性</span></span><br><span class="line">    headers[name] = value</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> headers</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>打印结果如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">host</span>: <span class="string">'localhost'</span>,</span><br><span class="line">  connection: <span class="string">'Upgrade'</span>,</span><br><span class="line">  pragma: <span class="string">'no-cache'</span>,</span><br><span class="line">  <span class="string">'cache-control'</span>: <span class="string">'no-cache'</span>,</span><br><span class="line">  upgrade: <span class="string">'websocket'</span>,</span><br><span class="line">  origin: <span class="string">'file'</span>,</span><br><span class="line">  <span class="string">'sec-websocket-version'</span>: <span class="string">'13'</span>,</span><br><span class="line">  <span class="string">'user-agent'</span>:</span><br><span class="line">   <span class="string">'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'</span>,</span><br><span class="line">  <span class="string">'accept-encoding'</span>: <span class="string">'gzip, deflate, br'</span>,</span><br><span class="line">  <span class="string">'accept-language'</span>: <span class="string">'zh-CN,zh;q=0.9'</span>,</span><br><span class="line">  cookie:</span><br><span class="line">   <span class="string">'_ga=GA1.1.1892261700.1545540050; _gid=GA1.1.585339125.1552405260'</span>,</span><br><span class="line">  <span class="string">'sec-websocket-key'</span>: <span class="string">'TipyPZNW+KNvV3fePNpriw=='</span>,</span><br><span class="line">  <span class="string">'sec-websocket-extensions'</span>: <span class="string">'permessage-deflate; client_max_window_bits'</span> &#125;</span><br></pre></td></tr></table></figure>
<h2 id="根据请求头参数，判断是否WebSocket请求"><a href="#根据请求头参数，判断是否WebSocket请求" class="headerlink" title="根据请求头参数，判断是否WebSocket请求"></a>根据请求头参数，判断是否WebSocket请求</h2><p>根据<code>headers[&#39;upgrade&#39;] !== &#39;websocket&#39;</code>，判断该HTTP连接是否可升级为WebSocket，若可以升级，表示为WebSocket请求。<br>根据<code>headers[&#39;sec-websocket-version&#39;] !== &#39;13&#39;</code>，判断WebSocket的版本是否为13，以免因为版本不同出现兼容问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">socket.once(<span class="string">'data'</span>, (buffer) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 接收到HTTP请求头数据</span></span><br><span class="line">  <span class="keyword">const</span> str = buffer.toString()</span><br><span class="line">  <span class="built_in">console</span>.log(str)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 4. 将请求头数据转为对象</span></span><br><span class="line">  <span class="keyword">const</span> headers = parseHeader(str)</span><br><span class="line">  <span class="built_in">console</span>.log(headers)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 5. 判断请求是否为WebSocket连接</span></span><br><span class="line">  <span class="keyword">if</span> (headers[<span class="string">'upgrade'</span>] !== <span class="string">'websocket'</span>) &#123;</span><br><span class="line">    <span class="comment">// 若当前请求不是WebSocket连接，则关闭连接</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'非WebSocket连接'</span>)</span><br><span class="line">    socket.end()</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (headers[<span class="string">'sec-websocket-version'</span>] !== <span class="string">'13'</span>) &#123;</span><br><span class="line">    <span class="comment">// 判断WebSocket版本是否为13，防止是其他版本，造成兼容错误</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'WebSocket版本错误'</span>)</span><br><span class="line">    socket.end()</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 请求为WebSocket连接时，进一步处理</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="校验Sec-WebSocket-Key，完成连接"><a href="#校验Sec-WebSocket-Key，完成连接" class="headerlink" title="校验Sec-WebSocket-Key，完成连接"></a>校验Sec-WebSocket-Key，完成连接</h2><p>根据协议规定的方式，向前端返回一个请求头，完成建立WebSocket连接的过程。</p>
<p>若客户端校验结果正确，在控制台的Network模块可以看到HTTP请求的状态码变为101 Switching Protocols，同时客户端的ws.onopen事件被触发。</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/3/13/16977a4514369b43?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="console"></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">socket.once(<span class="string">'data'</span>, (buffer) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 接收到HTTP请求头数据</span></span><br><span class="line">  <span class="keyword">const</span> str = buffer.toString()</span><br><span class="line">  <span class="built_in">console</span>.log(str)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 4. 将请求头数据转为对象</span></span><br><span class="line">  <span class="keyword">const</span> headers = parseHeader(str)</span><br><span class="line">  <span class="built_in">console</span>.log(headers)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 5. 判断请求是否为WebSocket连接</span></span><br><span class="line">  <span class="keyword">if</span> (headers[<span class="string">'upgrade'</span>] !== <span class="string">'websocket'</span>) &#123;</span><br><span class="line">    <span class="comment">// 若当前请求不是WebSocket连接，则关闭连接</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'非WebSocket连接'</span>)</span><br><span class="line">    socket.end()</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (headers[<span class="string">'sec-websocket-version'</span>] !== <span class="string">'13'</span>) &#123;</span><br><span class="line">    <span class="comment">// 判断WebSocket版本是否为13，防止是其他版本，造成兼容错误</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'WebSocket版本错误'</span>)</span><br><span class="line">    socket.end()</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 6. 校验Sec-WebSocket-Key，完成连接</span></span><br><span class="line">      <span class="comment">/* </span></span><br><span class="line"><span class="comment">        协议中规定的校验用GUID，可参考如下链接：</span></span><br><span class="line"><span class="comment">        https://tools.ietf.org/html/rfc6455#section-5.5.2</span></span><br><span class="line"><span class="comment">        https://stackoverflow.com/questions/13456017/what-does-258eafa5-e914-47da-95ca-c5ab0dc85b11-means-in-websocket-protocol</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">      <span class="keyword">const</span> GUID = <span class="string">'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'</span></span><br><span class="line">      <span class="keyword">const</span> key = headers[<span class="string">'sec-websocket-key'</span>]</span><br><span class="line">      <span class="keyword">const</span> hash = crypto.createHash(<span class="string">'sha1'</span>)  <span class="comment">// 创建一个签名算法为sha1的哈希对象</span></span><br><span class="line"></span><br><span class="line">      hash.update(<span class="string">`<span class="subst">$&#123;key&#125;</span><span class="subst">$&#123;GUID&#125;</span>`</span>)  <span class="comment">// 将key和GUID连接后，更新到hash</span></span><br><span class="line">      <span class="keyword">const</span> result = hash.digest(<span class="string">'base64'</span>) <span class="comment">// 生成base64字符串</span></span><br><span class="line">	  <span class="keyword">const</span> header = <span class="string">`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-Websocket-Accept: <span class="subst">$&#123;result&#125;</span>\r\n\r\n`</span> <span class="comment">// 生成供前端校验用的请求头</span></span><br><span class="line"></span><br><span class="line">      socket.write(header)  <span class="comment">// 返回HTTP头，告知客户端校验结果，HTTP状态码101表示切换协议：https://httpstatuses.com/101。</span></span><br><span class="line">      <span class="comment">// 若客户端校验结果正确，在控制台的Network模块可以看到HTTP请求的状态码变为101 Switching Protocols，同时客户端的ws.onopen事件被触发。</span></span><br><span class="line">      <span class="built_in">console</span>.log(header)</span><br><span class="line">      </span><br><span class="line">      <span class="comment">// 处理聊天数据</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br></pre></td></tr></table></figure>
<h2 id="建立连接后，通过data事件接收客户端的数据并处理"><a href="#建立连接后，通过data事件接收客户端的数据并处理" class="headerlink" title="建立连接后，通过data事件接收客户端的数据并处理"></a>建立连接后，通过data事件接收客户端的数据并处理</h2><p>连接开始后，可以在控制台的Network模块看到，该连接会一直保留在pending状态，直到连接断开。</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/3/13/16977a4524cc9dca?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="console1"></p>
<p>此时可以通过data事件处理客户端的数据，但此时双方通信的数据为二进制，需要按照其格式进行处理后才可以正常使用。</p>
<p>格式如下：</p>
<p><img src="https://user-gold-cdn.xitu.io/2019/3/13/16977a45146a18d6?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="console2"></p>
<p>处理收到的数据：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decodeWsFrame</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> start = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">let</span> frame = &#123;</span><br><span class="line">    isFinal: (data[start] &amp; <span class="number">0x80</span>) === <span class="number">0x80</span>,</span><br><span class="line">    opcode: data[start++] &amp; <span class="number">0xF</span>,</span><br><span class="line">    masked: (data[start] &amp; <span class="number">0x80</span>) === <span class="number">0x80</span>,</span><br><span class="line">    payloadLen: data[start++] &amp; <span class="number">0x7F</span>,</span><br><span class="line">    maskingKey: <span class="string">''</span>,</span><br><span class="line">    payloadData: <span class="literal">null</span></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (frame.payloadLen === <span class="number">126</span>) &#123;</span><br><span class="line">    frame.payloadLen = (data[start++] &lt;&lt; <span class="number">8</span>) + data[start++];</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (frame.payloadLen === <span class="number">127</span>) &#123;</span><br><span class="line">    frame.payloadLen = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">7</span>; i &gt;= <span class="number">0</span>; --i) &#123;</span><br><span class="line">      frame.payloadLen += (data[start++] &lt;&lt; (i * <span class="number">8</span>));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (frame.payloadLen) &#123;</span><br><span class="line">    <span class="keyword">if</span> (frame.masked) &#123;</span><br><span class="line">      <span class="keyword">const</span> maskingKey = [</span><br><span class="line">        data[start++],</span><br><span class="line">        data[start++],</span><br><span class="line">        data[start++],</span><br><span class="line">        data[start++]</span><br><span class="line">      ];</span><br><span class="line"></span><br><span class="line">      frame.maskingKey = maskingKey;</span><br><span class="line"></span><br><span class="line">      frame.payloadData = data</span><br><span class="line">        .slice(start, start + frame.payloadLen)</span><br><span class="line">        .map(<span class="function">(<span class="params">byte, idx</span>) =&gt;</span> byte ^ maskingKey[idx % <span class="number">4</span>]);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      frame.payloadData = data.slice(start, start + frame.payloadLen);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.dir(frame)</span><br><span class="line">  <span class="keyword">return</span> frame;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>处理发出的数据：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encodeWsFrame</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> isFinal = data.isFinal !== <span class="literal">undefined</span> ? data.isFinal : <span class="literal">true</span>,</span><br><span class="line">    opcode = data.opcode !== <span class="literal">undefined</span> ? data.opcode : <span class="number">1</span>,</span><br><span class="line">    payloadData = data.payloadData ? Buffer.from(data.payloadData) : <span class="literal">null</span>,</span><br><span class="line">    payloadLen = payloadData ? payloadData.length : <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> frame = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (isFinal) frame.push((<span class="number">1</span> &lt;&lt; <span class="number">7</span>) + opcode);</span><br><span class="line">  <span class="keyword">else</span> frame.push(opcode);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (payloadLen &lt; <span class="number">126</span>) &#123;</span><br><span class="line">    frame.push(payloadLen);</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (payloadLen &lt; <span class="number">65536</span>) &#123;</span><br><span class="line">    frame.push(<span class="number">126</span>, payloadLen &gt;&gt; <span class="number">8</span>, payloadLen &amp; <span class="number">0xFF</span>);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    frame.push(<span class="number">127</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">7</span>; i &gt;= <span class="number">0</span>; --i) &#123;</span><br><span class="line">      frame.push((payloadLen &amp; (<span class="number">0xFF</span> &lt;&lt; (i * <span class="number">8</span>))) &gt;&gt; (i * <span class="number">8</span>));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  frame = payloadData ? Buffer.concat([Buffer.from(frame), payloadData]) : Buffer.from(frame);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.dir(decodeWsFrame(frame));</span><br><span class="line">  <span class="keyword">return</span> frame;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对聊天数据进行处理：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">socket.once(<span class="string">'data'</span>, (buffer) =&gt; &#123;</span><br><span class="line">  <span class="comment">// 接收到HTTP请求头数据</span></span><br><span class="line">  <span class="keyword">const</span> str = buffer.toString()</span><br><span class="line">  <span class="built_in">console</span>.log(str)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 4. 将请求头数据转为对象</span></span><br><span class="line">  <span class="keyword">const</span> headers = parseHeader(str)</span><br><span class="line">  <span class="built_in">console</span>.log(headers)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 5. 判断请求是否为WebSocket连接</span></span><br><span class="line">  <span class="keyword">if</span> (headers[<span class="string">'upgrade'</span>] !== <span class="string">'websocket'</span>) &#123;</span><br><span class="line">    <span class="comment">// 若当前请求不是WebSocket连接，则关闭连接</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'非WebSocket连接'</span>)</span><br><span class="line">    socket.end()</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (headers[<span class="string">'sec-websocket-version'</span>] !== <span class="string">'13'</span>) &#123;</span><br><span class="line">    <span class="comment">// 判断WebSocket版本是否为13，防止是其他版本，造成兼容错误</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'WebSocket版本错误'</span>)</span><br><span class="line">    socket.end()</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 6. 校验Sec-WebSocket-Key，完成连接</span></span><br><span class="line">      <span class="comment">/* </span></span><br><span class="line"><span class="comment">        协议中规定的校验用GUID，可参考如下链接：</span></span><br><span class="line"><span class="comment">        https://tools.ietf.org/html/rfc6455#section-5.5.2</span></span><br><span class="line"><span class="comment">        https://stackoverflow.com/questions/13456017/what-does-258eafa5-e914-47da-95ca-c5ab0dc85b11-means-in-websocket-protocol</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">      <span class="keyword">const</span> GUID = <span class="string">'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'</span></span><br><span class="line">      <span class="keyword">const</span> key = headers[<span class="string">'sec-websocket-key'</span>]</span><br><span class="line">      <span class="keyword">const</span> hash = crypto.createHash(<span class="string">'sha1'</span>)  <span class="comment">// 创建一个签名算法为sha1的哈希对象</span></span><br><span class="line"></span><br><span class="line">      hash.update(<span class="string">`<span class="subst">$&#123;key&#125;</span><span class="subst">$&#123;GUID&#125;</span>`</span>)  <span class="comment">// 将key和GUID连接后，更新到hash</span></span><br><span class="line">      <span class="keyword">const</span> result = hash.digest(<span class="string">'base64'</span>) <span class="comment">// 生成base64字符串</span></span><br><span class="line">	  <span class="keyword">const</span> header = <span class="string">`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-Websocket-Accept: <span class="subst">$&#123;result&#125;</span>\r\n\r\n`</span> <span class="comment">// 生成供前端校验用的请求头</span></span><br><span class="line"></span><br><span class="line">      socket.write(header)  <span class="comment">// 返回HTTP头，告知客户端校验结果，HTTP状态码101表示切换协议：https://httpstatuses.com/101。</span></span><br><span class="line">      <span class="comment">// 若客户端校验结果正确，在控制台的Network模块可以看到HTTP请求的状态码变为101 Switching Protocols，同时客户端的ws.onopen事件被触发。</span></span><br><span class="line">      <span class="built_in">console</span>.log(header)</span><br><span class="line">      </span><br><span class="line">      <span class="comment">// 7. 建立连接后，通过data事件接收客户端的数据并处理</span></span><br><span class="line">      socket.on(<span class="string">'data'</span>, (buffer) =&gt; &#123;</span><br><span class="line">        <span class="keyword">const</span> data = decodeWsFrame(buffer)</span><br><span class="line">        <span class="built_in">console</span>.log(data)</span><br><span class="line">        <span class="built_in">console</span>.log(data.payloadData &amp;&amp; data.payloadData.toString())</span><br><span class="line"></span><br><span class="line">        <span class="comment">// opcode为8，表示客户端发起了断开连接</span></span><br><span class="line">        <span class="keyword">if</span> (data.opcode === <span class="number">8</span>) &#123;</span><br><span class="line">          socket.end()  <span class="comment">// 与客户端断开连接</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">// 接收到客户端数据时的处理，此处默认为返回接收到的数据。</span></span><br><span class="line">          socket.write(encodeWsFrame(&#123; <span class="attr">payloadData</span>: <span class="string">`服务端接收到的消息为：<span class="subst">$&#123;data.payloadData ? data.payloadData.toString() : <span class="string">''</span>&#125;</span>`</span> &#125;))</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br></pre></td></tr></table></figure>
<p>这样，一个简单的基于WebSocket的聊天应用就创建完成了，在启动服务器后，可以打开index.html看到效果。</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#WebSocket的优势"><span class="toc-number">1.</span> <span class="toc-text">WebSocket的优势</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Socket-io"><span class="toc-number">1.1.</span> <span class="toc-text">Socket.io</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#使用Socket-io建立一个WebSocket应用"><span class="toc-number">1.2.</span> <span class="toc-text">使用Socket.io建立一个WebSocket应用</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#原生实现WebSocket应用"><span class="toc-number">2.</span> <span class="toc-text">原生实现WebSocket应用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#服务端创建一个Net服务器"><span class="toc-number">2.1.</span> <span class="toc-text">服务端创建一个Net服务器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Web端创建一个WebSocket链接"><span class="toc-number">2.2.</span> <span class="toc-text">Web端创建一个WebSocket链接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#服务端使用socket-once，触发一次data事件处理HTTP请求头数据"><span class="toc-number">2.3.</span> <span class="toc-text">服务端使用socket.once，触发一次data事件处理HTTP请求头数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#将请求头字符串转为对象"><span class="toc-number">2.4.</span> <span class="toc-text">将请求头字符串转为对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#根据请求头参数，判断是否WebSocket请求"><span class="toc-number">2.5.</span> <span class="toc-text">根据请求头参数，判断是否WebSocket请求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#校验Sec-WebSocket-Key，完成连接"><span class="toc-number">2.6.</span> <span class="toc-text">校验Sec-WebSocket-Key，完成连接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#建立连接后，通过data事件接收客户端的数据并处理"><span class="toc-number">2.7.</span> <span class="toc-text">建立连接后，通过data事件接收客户端的数据并处理</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
